from modules.SRRun.ActivityInfo import ActivityInfo
from modules.SRRun.PackageInfo import PackageInfo
from modules.common.Logger import Logger
from pathlib import Path


def load_activity_list(logger: Logger, activity_list):
    """
    读取  pkg###pkg/Activity  每行，返回 {'default':[PackageInfo,...]}
    """
    logger.info(f"load_activity_list, activity_list: {activity_list}")
    package_info_list = []
    
    # 检查文件是否存在
    activity_path = Path(activity_list)
    if not activity_path.exists():
        logger.error(f"Activity 列表文件不存在: {activity_list}")
        raise FileNotFoundError(f"Activity 列表文件不存在: {activity_list}")

    try:
        with open(activity_path, encoding="utf-8") as fp:
            for line_num, line in enumerate(fp, 1):
                line = line.strip()
                if not line or '###' not in line:
                    logger.debug(f"跳过第 {line_num} 行: {line}")
                    continue
                    
                parts = line.split("###", 1)
                if len(parts) != 2:
                    logger.warning(f"第 {line_num} 行格式错误: {line}")
                    continue
                    
                package_name = parts[0].strip()
                activity_name = parts[1].strip()
                
                logger.debug(f"第 {line_num} 行: package_name: {package_name}, activity_name: {activity_name}")

                if package_name and activity_name:
                    try:
                        package_info = PackageInfo(package_name)
                        activity_info = ActivityInfo(activity_name)
                        package_info.append_activity(activity_info)
                        package_info_list.append(package_info)
                    except Exception as e:
                        logger.error(f"创建 PackageInfo 或 ActivityInfo 失败 (第 {line_num} 行): {e}")
                        continue
                else:
                    logger.warning(f"第 {line_num} 行 package_name 或 activity_name 为空: {line}")
                    
    except UnicodeDecodeError as e:
        logger.error(f"文件编码错误: {e}")
        raise ValueError(f"文件编码错误，请使用 UTF-8 编码: {activity_list}")
    except Exception as e:
        logger.error(f"读取文件失败: {e}")
        raise
    
    if not package_info_list:
        logger.warning(f"未找到有效的 activity 配置")
        
    logger.info(f"成功加载 {len(package_info_list)} 个应用配置")
    return package_info_list
